<?php

namespace app\api\controller\kuerp\order;

use app\common\controller\Api;

use think\Db;
use app\api\library\kuerp\Auth;
use app\common\service\OrangeMoneyService;
use app\common\service\PayPalService;
use think\Log;

class Payment extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $auth_s;
    protected $goods_image = '/assets/addons/kuerp/img/noimage.png';
    protected $price_status;

    public function _initialize()
    {
        parent::_initialize();
        $this->auth_s = new Auth();
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $this->auth_s->init($token);
        $this->price_status = Db::name('kuerp_user_config')->where(['name' => 'price_status'])->value('value'); //是否显示价格
    }

    public function pay()
    {
        $user = $this->auth_s->getUserinfo();
        if (!isset($user['id'])) {
            $this->error(__('Please login'), '', 250);
        }
        $pay_status = Db::name('kuerp_user_config')->where(['name' => 'pay_status'])->value('value');
        if ($pay_status != 1) {
            $this->error(__('System not enabled'), '', 250);
        }
        $data = input();
        $order_num = isset($data['order_num']) ? $data['order_num'] : '';
        if (empty($order_num)) {
            $this->error(__('Please select order to pay'), '', 400);
        }
        $where = [];
        $where['order_num'] = $order_num;
        $where['user_id'] = $user['id'];
        $where['pay_status'] = '0';
        $order = Db::name('kuerp_user_order')->where($where)->find();
        if (empty($order)) {
            $this->error(__('Order not found'), '', 400);
        }

        $payType = $this->request->param('pay_type'); // 2:PAYPAL, 3:ORANGE MONEY

        if (!$payType) {
            $this->error(__('Please select payment method'), '', 400);
        }

        if ($payType == 2) {
            // PAYPAL
            $payPal = new PayPalService();
            $result = $payPal->createPayment($order['order_price'], 'USD', "order:{$order['order_num']}");

            if ($result['success']) {
                // 记录支付日志
                return json([
                    'code' => 0,
                    'msg' => 'success',
                    'data' => [
                        'approval_url' => $result['approval_url'],
                        'payment_id' => $result['payment_id']
                    ]
                ]);
            } else {
                return json(['code' => 1002, 'msg' => $result['message']]);
            }
        } else if ($payType == 3) {
            //ORANGE MONEY 
            $phone = $this->request->param('phone'); // 客户手机号
            if (empty($phone)) {
                $this->error(__('Please provide phone number'), '', 400);
            }

            $orangeMoney = new OrangeMoneyService();
            $result = $orangeMoney->initiatePayment($order['order_price'], $order['order_num'], $phone);

            if ($result['success']) {
                // 记录支付日志
                $this->recordPaymentLog($order['order_num'], $result['data']);
                
                return json([
                    'code' => 0,
                    'msg' => 'success',
                    'data' => $result['data']
                ]);
            } else {
                return json(['code' => 1002, 'msg' => $result['message']]);
            }
        }

        // return $this->success(__('Success'), ['url' => 'http://payment.cc'], 200);
    }

    // 支付成功回调
    public function returnUrl()
    {
        $paymentId = $this->request->param('paymentId');
        $PayerID = $this->request->param('PayerID');

        $transactionId = $this->request->param('transaction_id');
        $status = $this->request->param('status');
        $orderId = $this->request->param('order_id');

        if ($paymentId && $PayerID) {

            $payPal = new PayPalService();
            $result = $payPal->executePayment($paymentId, $PayerID);

            if ($result['success']) {
                // 验证支付状态
                $statusResult = $payPal->getPaymentStatus($paymentId);
                if ($statusResult['success'] && $statusResult['status'] == 'approved') {
                    // 更新订单状态
                    $this->updateOrderStatus($orderId, 'paid');
                }
            }
        } else if ($transactionId && $status && $orderId) {
            // 验证回调数据
            $orange = new OrangeMoneyService();
            $checkResult = $orange->checkPaymentStatus($transactionId);

            if ($checkResult['success'] && $checkResult['data']['status'] == 'SUCCESS') {
                // 更新订单状态
                $this->updateOrderStatus($orderId, 'paid');
            }
        }
    }

    // 支付取消回调
    public function cancelUrl()
    {
        return 'cancelUrl method';
        //   return redirect('/order/cancel');
    }

    // 异步通知处理（IPN）
    // 替换原来的 IPN 处理方法
    public function ipn()
    {
        // 获取原始 POST 数据
        $rawPostData = file_get_contents('php://input');

        try {
            $ipnService = new \app\common\service\PayPalIPNService();
            // 验证 IPN（第二个参数为环境：sandbox 或 production）
            $isVerified = $ipnService->verifyIPN($rawPostData, 'sandbox');

            if ($isVerified) {
                // 解析 IPN 数据
                $ipnData = $_POST;

                // 处理支付成功逻辑（例如验证 payment_status 为 Completed）
                if ($ipnData['payment_status'] === 'Completed') {
                    // 更新订单状态等操作
                    // ...
                }

                http_response_code(200);
                echo "VERIFIED";
            } else {
                http_response_code(400);
                echo "INVALID";
            }
        } catch (\Exception $e) {
            http_response_code(500);
            echo "ERROR: " . $e->getMessage();
        }
        exit;
    }
    // 异步通知处理
    public function notify()
    {
        $rawData = file_get_contents('php://input');
        $data = json_decode($rawData, true);

        // 记录通知日志
        $this->recordNotifyLog($data);

        // 验证通知真实性
        if ($this->verifyNotify($data)) {
            if ($data['status'] == 'SUCCESS') {
                // 处理成功支付
                $this->updateOrderStatus($data['order_id'], 'paid');
            }
            // 返回成功响应
            echo 'OK';
        } else {
            http_response_code(400);
            echo 'ERROR';
        }
        exit;
    }

    // 辅助方法：记录日志、更新订单等
    private function recordPaymentLog($orderId, $data)
    {
        // 实现日志记录逻辑
        Log::record('Payment log for order ' . $orderId . ': ' . json_encode($data), 'pay');
    }

    private function recordNotifyLog($data)
    {
        // 实现日志记录逻辑
        Log::record('Payment notify: ' . json_encode($data), 'pay');
    }

    private function updateOrderStatus($orderId, $status)
    {
        // 实现订单状态更新逻辑
    }

    private function verifyNotify($data)
    {
        // 实现通知验证逻辑
        return true;
    }
}
